<?php

namespace app\api\controller;

use app\api\service\ArtworkService;
use app\common\controller\ApiBase;
use app\common\model\user\Artwork as UserArtworkModel;
use app\common\model\user\ArtworkAttribute as UserArtworkAttributeModel;
use app\common\validate\user\Artwork as UserArtworkValidate;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;

class Artwork extends ApiBase
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    //作品id
    public function index()
    {
        $this->checkRequestParam(UserArtworkValidate::class);

        $userArtwork = UserArtworkModel
            ::where([
                'id'      => $this->request->param('id'),
                'user_id' => $this->auth->id,
            ])
            ->with(['artwork_attribute' => ['fbx']])
            ->find();
        if (!$userArtwork) {
            $this->error('数据不存在');
        }
        if ($userArtwork['status'] != UserArtworkModel::STATUS_NORMAL) {
            $this->error('作品状态错误');
        }

        return $this->success('成功', $userArtwork);
    }

    //作品列表
    public function list()
    {
        $this->checkRequestParam(UserArtworkValidate::class);

        $where = [
            'user_id' => $this->auth->id,
        ];
        $userArtwork = UserArtworkModel
            ::where($where)
            ->with([
                'artwork_attribute' /* => ['fbx']*/
            ])
            ->paginate($this->getPaginate());
        $list = $userArtwork->items();
        $count = $userArtwork->total();

        return $this->success('成功', ['count' => $count, 'list' => $list]);
    }

    //添加作品
    public function add()
    {
        $this->checkRequestParam(UserArtworkValidate::class);

        $count = UserArtworkModel::where([
                'user_id' => $this->auth->id,
                'status'  => UserArtworkModel::STATUS_NORMAL,
            ])->count();
        $user_artwork_limit = Config::get('site.user_artwork_max');
        if ($count >= $user_artwork_limit) {
            $this->error("作品数量不能超过 {$user_artwork_limit} 个");
        }

        $userArtwork = UserArtworkModel::create([
            'user_id' => $this->auth->id,
            'name'    => $this->request->param('name'),
            'status'  => UserArtworkModel::STATUS_NORMAL,
        ]);
        if ($userArtwork) {
            $this->success('success', ['user_artwork' => $userArtwork]);
        } else {
            $this->error('保存失败');
        }
    }

    public function edit()
    {
        $this->checkRequestParam(UserArtworkValidate::class);

        $userArtwork = UserArtworkModel::where([
            'id'      => $this->request->param('id'),
            'user_id' => $this->auth->id,
        ])->find();
        if (!$userArtwork) {
            $this->error('作品不存在');
        }
        if ($userArtwork['status'] != UserArtworkModel::STATUS_NORMAL) {
            $this->error('作品状态错误');
        }

        $userArtwork->name = $this->request->param('name');
        if ($userArtwork->save()) {
            $this->success('success', ['user_artwork' => $userArtwork]);
        } else {
            $this->error('保存失败');
        }
    }

    // 删除作品
    public function del()
    {
        $this->checkRequestParam(UserArtworkValidate::class);

        $list = UserArtworkModel::where([
            'id'      => ['in', explode(',', $this->request->param('ids'))],
            'user_id' => $this->auth->id,
        ])->select();

        if (!$list) {
            $this->error('数据不存在');
        }
        $ids = collection($list)->column('id');
        Db::startTrans();
        try {
            UserArtworkModel::destroy(['id' => ['in', $ids]]);
            UserArtworkAttributeModel::destroy(['artwork_id' => ['in', $ids]]);

            Db::commit();
            $this->success('删除成功', ['ids' => $ids]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    public function submitOrder()
    {
        $this->checkRequestParam(UserArtworkValidate::class);
        $param = $this->request->param();
        $userArtwork = UserArtworkModel::where([
            'id'      => $param['id'],
            'user_id' => $this->auth->id,
        ])->find();
        if (!$userArtwork) {
            $this->error('作品不存在');
        }

        $service = new ArtworkService();

        Db::startTrans();
        try {
            $order = $service->submitOrder($userArtwork, $this->auth->id);
            if (empty($order)) {
                Db::rollback();
                $this->error($service->getMsg());
            }

            Db::commit();
            $this->success('成功', ['order' => $order]);
        }catch (Exception $e) {
            Db::rollback();
            $this->errorTrace('提交作品订单失败。',$e);
        }


    }
}
